﻿namespace Zhaoxi.NET7.ASPNETCoreProject.Utility
{
    /// <summary>
    /// ASP.NET Core的中间件
    /// </summary>
    public class StaticPageMiddleware
    {
        #region Identity
        private readonly RequestDelegate _next;
        private string _directoryPath = null;
        private bool _supportDelete = false;
        private bool _supportWarmup = false;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="next">下一个中间件</param>
        /// <param name="directoryPath"></param>
        /// <param name="supportDelete"></param>
        /// <param name="supportWarmup"></param>
        public StaticPageMiddleware(RequestDelegate next, string directoryPath, bool supportDelete, bool supportWarmup)
        {
            this._next = next;
            this._directoryPath = directoryPath;
            this._supportDelete = supportDelete;
            this._supportWarmup = supportWarmup;
        }
        #endregion
        /// <summary>
        /// 中间件的动作执行
        /// 需要读取响应的response stream
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            Console.WriteLine($"This is StaticPageMiddleware InvokeAsync {context.Request.Path.Value}");
            if (context.Request.Path.Value!.StartsWith("/item/", StringComparison.InvariantCultureIgnoreCase))
            {
                #region context.Response.Body
                //stream读取问题---中间件默认不能读取---狸猫换太子
                var originalStream = context.Response.Body;
                using (var copyStream = new MemoryStream())
                {
                    context.Response.Body = copyStream;
                    await _next(context);//后续的常规流程，正常请求响应

                    copyStream.Position = 0;
                    var reader = new StreamReader(copyStream);
                    var content = await reader.ReadToEndAsync();
                    string url = context.Request.Path.Value;

                    this.SaveHtml(url, content);

                    copyStream.Position = 0;
                    await copyStream.CopyToAsync(originalStream);
                    context.Response.Body = originalStream;
                }
                #endregion
            }
            else
            {
                await this._next(context);
            }

        }

        private void SaveHtml(string url, string html)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(html))
                    return;
                if (!url.EndsWith(".html"))
                    return;

                if (Directory.Exists(_directoryPath) == false)
                    Directory.CreateDirectory(_directoryPath);

                var totalPath = Path.Combine(_directoryPath, url.Split("/").Last());
                File.WriteAllText(totalPath, html);//直接覆盖
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

    }
}
